import React, { useState, useEffect } from 'react';
import { Card, Tag, Spin, message, Button, Popconfirm, Typography, Menu } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined, BookOutlined } from '@ant-design/icons';
import { sopService, SOP_CUSTOMER_PROFILES } from '../services/sopService';
import { SopChain } from '../types/sop';
import SopStrategyModal from './SopStrategyModal';

const { Title, Text } = Typography;

const SopStrategyTab: React.FC = () => {
  const [sopChains, setSopChains] = useState<SopChain[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeGroup, setActiveGroup] = useState<string>(SOP_CUSTOMER_PROFILES[0]);
  const [modalVisible, setModalVisible] = useState(false);
  const [availableNodes, setAvailableNodes] = useState<Record<string, string[]>>({});
  const [nodesLoading, setNodesLoading] = useState(false);
  const [editingStrategy, setEditingStrategy] = useState<SopChain | null>(null);

  // 根据选中的客群过滤策略
  const getFilteredStrategies = () => {
    return sopChains.filter(chain => chain.customer_profile === activeGroup);
  };

  // 获取分类统计
  const getCategoryCount = (category: string) => {
    return sopChains.filter(chain => chain.customer_profile === category).length;
  };

  // 加载SOP策略数据
  const loadSopChains = async () => {
    try {
      setLoading(true);
      const chains = await sopService.getSopChains();
      setSopChains(chains);
    } catch (error) {
      console.error('加载SOP策略失败:', error);
      message.error('加载SOP策略失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 加载节点库数据
  const loadAvailableNodes = async () => {
    try {
      setNodesLoading(true);
      const nodes = await sopService.getSopNodes();
      setAvailableNodes(nodes);
    } catch (error) {
      console.error('加载节点库失败:', error);
      message.error('加载节点库失败，请稍后重试');
    } finally {
      setNodesLoading(false);
    }
  };

  // 处理新建策略
  const handleCreateNewStrategy = () => {
    setEditingStrategy(null);
    setModalVisible(true);
  };

  // 处理编辑策略
  const handleEditStrategy = (strategy: SopChain) => {
    setEditingStrategy(strategy);
    setModalVisible(true);
  };

  // 处理删除策略
  const handleDeleteStrategy = async (strategy: SopChain) => {
    try {
      const result = await sopService.deleteSopChain(strategy.chain_id);
      if (result.success) {
        message.success('删除SOP策略成功');
        // 重新加载策略列表
        loadSopChains();
      } else {
        message.error(result.error || '删除策略失败');
      }
    } catch (error) {
      console.error('删除SOP策略失败:', error);
      message.error('删除策略失败，请重试');
    }
  };

  // 处理模态框取消
  const handleModalCancel = () => {
    setModalVisible(false);
    setEditingStrategy(null);
  };

  // 处理策略创建或更新成功
  const handleStrategySuccess = () => {
    setModalVisible(false);
    setEditingStrategy(null);
    // 重新加载策略列表
    loadSopChains();
  };

  // 渲染SOP节点链路
  const renderSopNodes = (nodes: SopChain['nodes']) => {
    if (!nodes || nodes.length === 0) {
      return <span className="text-gray-400">暂无节点配置</span>;
    }

    return (
      <div className="flex items-center overflow-x-auto pb-2 text-sm">
        {nodes
          .sort((a, b) => a.order - b.order)
          .map((node, index) => (
            <React.Fragment key={`${node.order}-${index}`}>
              <span className="whitespace-nowrap" title={`阶段：${node.stage}`}>
                {node.node}
              </span>
              {index < nodes.length - 1 && (
                <span className="mx-2 text-gray-400">→</span>
              )}
            </React.Fragment>
          ))}
      </div>
    );
  };

  // 组件挂载时加载数据
  useEffect(() => {
    // 并行加载策略数据和节点库数据
    Promise.all([
      loadSopChains(),
      loadAvailableNodes()
    ]);
  }, []);

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <Spin size="large" />
        <span className="ml-3 text-gray-600">正在加载经营策略...</span>
      </div>
    );
  }

  const filteredStrategies = getFilteredStrategies();

  return (
    <div className="marketing-strategy-library flex" style={{ height: '100%' }}>
      {/* 左侧分类菜单 */}
      <div className="w-64 bg-gray-50 border-r border-gray-200 p-4">
        <div className="mb-6">
          <Title level={4} className="!mb-4 text-gray-800">客群分类</Title>
        </div>
        <Menu
          mode="inline"
          selectedKeys={[activeGroup]}
          className="bg-transparent border-none"
          items={SOP_CUSTOMER_PROFILES.map(group => ({
            key: group,
            label: (
              <div className="flex justify-between items-center">
                <span>{group}</span>
                <Tag color="blue" className="ml-2">
                  {getCategoryCount(group)}
                </Tag>
              </div>
            ),
            onClick: () => setActiveGroup(group)
          }))}
        />
      </div>

      {/* 右侧内容区 */}
      <div className="flex-1 flex flex-col">
        {/* 顶部操作区 */}
        <div className="mb-3 flex justify-between items-center px-6 py-4 bg-white border-b border-gray-200">
          <div>
            <Title level={3} className="!mb-2">{activeGroup}</Title>
            <Text type="secondary" className="text-sm">
              共有 <span className="font-semibold text-blue-600">{filteredStrategies.length}</span> 个SOP策略
            </Text>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreateNewStrategy}
            className="shadow-sm"
            loading={nodesLoading}
            disabled={Object.keys(availableNodes).length === 0}
          >
            新建策略
          </Button>
        </div>

        {/* 卡片列表滚动区 */}
        <div className="flex-1 px-6 pb-6" style={{ overflowY: 'auto' }}>
          {loading ? (
            <div className="text-center py-12">
              <div className="animate-spin w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full mx-auto mb-4"></div>
              <Text className="text-gray-600">正在加载SOP策略...</Text>
            </div>
          ) : filteredStrategies.length === 0 ? (
            <div className="text-center py-12">
              <BookOutlined className="text-4xl text-gray-400 mb-4" />
              <Title level={4} className="!mb-2 text-gray-500">暂无SOP策略</Title>
              <Text type="secondary">
                点击"新建策略"按钮开始创建您的第一个SOP策略
              </Text>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              {filteredStrategies.map((chain) => (
                <Card
                  key={chain.chain_id}
                  className="marketing-strategy-card hover:shadow-lg transition-all duration-300 flex flex-col"
                  size="small"
                  style={{
                    borderRadius: '12px',
                    background: 'linear-gradient(135deg, #ffffff 0%, #fafafa 100%)',
                    border: '1px solid #f0f0f0',
                    minHeight: 280,
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'space-between'
                  }}
                  actions={[
                    <Button
                      type="text"
                      icon={<EditOutlined />}
                      onClick={() => handleEditStrategy(chain)}
                      className="text-blue-500 hover:text-blue-700"
                    >
                      编辑
                    </Button>,
                    ...(chain.type === 'custom' ? [
                      <Popconfirm
                        key="delete"
                        title="确定删除这个SOP策略吗？"
                        onConfirm={() => handleDeleteStrategy(chain)}
                        okText="确定"
                        cancelText="取消"
                      >
                        <Button
                          type="text"
                          icon={<DeleteOutlined />}
                          className="text-red-500 hover:text-red-700"
                        >
                          删除
                        </Button>
                      </Popconfirm>
                    ] : [])
                  ]}
                >
                  <div className="space-y-3 flex flex-col h-full">
                    {/* 卡片头部 */}
                    <div className="flex justify-between items-start">
                      <div className="flex-1 pr-4">
                        <div className="flex items-center gap-2 mb-2">
                          <Title level={5} className="!mb-0 text-gray-900 line-clamp-2">
                            {chain.name}
                          </Title>
                        </div>
                        <div className="flex flex-wrap items-center gap-1 mb-2">
                          {chain.scenario && (
                            <Tag color="green" className="mb-1 text-xs">
                              {chain.scenario}
                            </Tag>
                          )}
                        </div>
                      </div>
                    </div>

                    {/* 策略描述 */}
                    <div className="mb-3" style={{ maxHeight: 80, overflowY: 'auto' }}>
                      <Text className="text-gray-600 text-sm leading-relaxed">
                        {chain.description}
                      </Text>
                    </div>

                    {/* SOP链路节点 */}
                    <div className="flex flex-wrap gap-1 mb-3">
                      <div className="w-full">
                        <Text className="text-gray-600 text-xs mb-1 block">经营链路:</Text>
                        <div className="text-xs text-gray-500">
                          {renderSopNodes(chain.nodes)}
                        </div>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* SOP策略创建/编辑模态框 */}
      <SopStrategyModal
        visible={modalVisible}
        onCancel={handleModalCancel}
        activeGroup={activeGroup}
        onSuccess={handleStrategySuccess}
        availableNodes={availableNodes}
        editingStrategy={editingStrategy}
      />
    </div>
  );
};

export default SopStrategyTab; 